package com.shigu.account.service;

import com.opentae.data.mall.beans.*;
import com.opentae.data.mall.examples.CashApplyExample;
import com.opentae.data.mall.examples.MallTradeExample;
import com.opentae.data.mall.examples.MallWalletRecordExample;
import com.opentae.data.mall.interfaces.*;
import com.shigu.MallResponse;
import com.shigu.PageResponse;
import com.shigu.account.enums.CashState;
import com.shigu.account.enums.MoneyRecordType;
import com.shigu.account.enums.WalletChangeType;
import com.shigu.account.exception.UtilsAccountException;
import com.shigu.account.vo.CommissionInfoResponse;
import com.shigu.account.vo.CommissionOrderVo;
import com.shigu.account.vo.CommissionVo;
import com.shigu.account.vo.WapCashVo;
import com.shigu.exceptions.WapException;
import com.shigu.paypwd.util.MD5Util;
import com.shigu.trade.enums.*;
import com.shigu.util.MoneyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/*
 * create by  过儿  2019-04-30
 * 用户余额和佣金管理
 */
@Service
public class UserMoneyService {

    @Autowired
    MallWalletRecordMapper mallWalletRecordMapper;
    @Autowired
    MallTradeMapper mallTradeMapper;
    @Autowired
    MallOrderMapper mallOrderMapper;
    @Autowired
    MallOrderRecordMapper mallOrderRecordMapper;
    @Autowired
    MallWalletMapper mallWalletMapper;
    @Autowired
    CashApplyMapper cashApplyMapper;
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    ManagerMallUserMapper managerMallUserMapper;
    @Autowired
    UserWxInfoMapper userWxInfoMapper;

    /**
     * @description 佣金明细
     * @author 郭尔
     * @date 2019-04-30 15:04
     */
    public PageResponse<CommissionVo> getCommissionList(Long mallUserId) {
        MallWalletRecordExample example = new MallWalletRecordExample();
        example.createCriteria().andUserIdEqualTo(mallUserId).andTypeEqualTo(WalletChangeType.money.getValue());
        example.setOrderByClause("change_time desc");

        List<MallWalletRecord> records = mallWalletRecordMapper.selectByExample(example);

        PageResponse<CommissionVo> response = new PageResponse<>();
        response.setData(records.stream().map(o -> {
            CommissionVo vo = new CommissionVo();
            vo.setCreateTime(o.getChangeTime());
            vo.setMoney(o.getChangeValue());
            vo.setText(o.getRemark());
            vo.setType(Double.valueOf(o.getChangeValue()) <= 0 ? 1 : 2);//小于0 收入 大于0 支出
            return vo;
        }).collect(Collectors.toList()));

        return response.success();
    }

    /**
     * @description 佣金清单
     * @author 郭尔
     * @date 2019-04-30 15:23
     */
    public PageResponse<CommissionOrderVo> getCommissionOrders(Long mallUserId, Integer page, Integer size) {
        //查询推广收益
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MallTradeExample example = new MallTradeExample();
        //筛选已订单过的支付(包含退款状态，所以是大于等于)
        example.createCriteria().andRewardIdEqualTo(mallUserId)
                                .andPayStatusGreaterThanOrEqualTo(TradePayStatus.HASPAY.getValue())
                                .andSourceEqualTo(TradeSource.GZH.getValue());

        example.setStartIndex((page - 1) * size);
        example.setEndIndex(size);
        example.setOrderByClause("tid desc");

        List<MallTrade> trades = mallTradeMapper.selectByConditionList(example);
        int total = mallTradeMapper.countByExample(example);

        PageResponse<CommissionOrderVo> response = new PageResponse<>();
        response.setData(trades.stream().map(o->{
            //查询order的商品信息
            MallOrder order = mallOrderMapper.selectOrderByTradeCode(o.getTradeCode());
            //查询订单时间
            Date createTime = mallOrderRecordMapper.selOrderTime(OrderTimeType.CREATETIME.getValue(), o.getTradeCode());
            Date finishTime = mallOrderRecordMapper.selOrderTime(OrderTimeType.RECEIVETIME.getValue(), o.getTradeCode());
            CommissionOrderVo vo = new CommissionOrderVo();

            vo.setTradeCode(order.getTradeCode());
            //判断状态
            vo.setTitle(order.getTitle());
            vo.setImgSrc(order.getImgUrl());
            vo.setGoodsPrice(order.getDiscount().toString());
            vo.setCommissionAmount(o.getReward().toString());
            vo.setPayAccount(o.getTotalMoney().toString());
            vo.setCreateTime(sdf.format(createTime));
            if(finishTime!=null){
                vo.setFinishTime(sdf.format(finishTime));
            }
            Integer state = sendStatusToState(o.getSendStatus());
            vo.setState(state);

            return vo;
        }).collect(Collectors.toList()));
        response.setTotal(total);
        response.setHasNext(total>page*size);

        return response.success();
    }


    private Integer sendStatusToState(Integer sendStatus){
        if(sendStatus == TradeSendStatus.RETREATING.getValue() ||
                sendStatus ==TradeSendStatus.RETREAT.getValue()){
            return 3;
        } else if(sendStatus == TradeSendStatus.SEND.getValue()){
            return 2;
        }
        return 1;
    }

    /**
     * @description 获取用户佣金详情
     * @author 郭尔
     * @date 2019-04-30 17:07
     */
    public CommissionInfoResponse getUserCommissionInfo(Long mallUserId){
        MallWallet wallet = mallWalletMapper.selByUserId(mallUserId);
        String commission = mallTradeMapper.userCommission(mallUserId);
        return new CommissionInfoResponse(wallet.getMallMoney().toString(),wallet.getTotalReward().toString(),commission).success();
    }

    /**
     *
     * @description 提现申请
     * @author 郭尔
     * @date 2019-05-05 15:02
     */
    public MallResponse applyWithdraw(Long mallUserId, String withdrawAccout, String psw) throws UtilsAccountException, WapException {

        judgeAccount(withdrawAccout);
        UserWxInfo wxInfo = userWxInfoMapper.selectByPrimaryKey(mallUserId);
        if(wxInfo==null){
            throw new WapException("请先绑定微信");
        }

        ManagerMallUser user = managerMallUserMapper.selectByPrimaryKey(mallUserId);
        if( !MD5Util.md5(psw).equals(user.getPayPwd()) ){
            throw new WapException("支付密码不正确");
        }
        Double amount = Double.valueOf(withdrawAccout);
        //减钱
        userAccountService.reduceMoney(mallUserId,amount, MoneyRecordType.cashApply.getText());

        CashApply apply = new CashApply();
        apply.setMallUserId(mallUserId);
        apply.setMoney(amount);
        apply.setApplyTime(new Date());
        cashApplyMapper.insertSelective(apply);

        return new MallResponse().success();
    }

    /**
     * todo 暂时没有做分页
     * @description 用户的提现记录
     * @author 郭尔
     * @date  12:39
     */
    public PageResponse<WapCashVo> getWithdrawRecordList(Integer page, Integer size, Long mallUserId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CashApplyExample example =  new CashApplyExample();
        example.createCriteria().andMallUserIdEqualTo(mallUserId);
        List<CashApply> list = cashApplyMapper.selectByExample(example);

        PageResponse<WapCashVo> response = new PageResponse<>();
        response.setData(list.stream().map(o->{
            CashState state = CashState.selByValue(o.getStatus());
            WapCashVo vo = new WapCashVo();
            vo.setCreateTime(sdf.format(o.getApplyTime()));
            vo.setWithdrawMoney(MoneyUtil.formatPriceMoney(o.getMoney()));
            vo.setType(o.getStatus());
            vo.setTypeName(state.getTitle());
            return vo;
        }).collect(Collectors.toList()));

        return response.success();
    }

    /**
     * @description 用户
     * @author 郭尔
     * @date 2019-11-12 10:59
     */
    public PageResponse<CommissionVo> voucherRecord(Long mallUserId){
        MallWalletRecordExample example = new MallWalletRecordExample();
        example.createCriteria().andUserIdEqualTo(mallUserId).andTypeEqualTo(WalletChangeType.voucher.getValue());
        example.setOrderByClause("change_time desc");

        List<MallWalletRecord> records = mallWalletRecordMapper.selectByExample(example);

        PageResponse<CommissionVo> response = new PageResponse<>();
        response.setData(records.stream().map(o -> {
            CommissionVo vo = new CommissionVo();
            vo.setCreateTime(o.getChangeTime());
            vo.setMoney(o.getChangeValue());
            vo.setText(o.getRemark());
            vo.setType(Double.valueOf(o.getChangeValue()) <= 0 ? 1 : 2);//小于0 收入 大于0 支出
            return vo;
        }).collect(Collectors.toList()));
        return response.success();
    }

    private void judgeAccount(String amount) throws WapException {
        Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
        Matcher isNum = pattern.matcher(amount);
        if(!isNum.matches()){
            throw new WapException("请输入纯数字");
        }
        if(Double.valueOf(amount)<1D){
            throw new WapException("提现金额不能少于1元");
        }
    }
}
